# -*- coding: utf-8 *-*

#   This file is part of Sql-Rice.
#
#    Sql-Rice is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 3 of the License, or
#    (at your option) any later version.
#
#    Sql-Rice is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with Sql-Rice; if not, write to the Free Software
#    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
import Tkinter
from gui.backend import MethodWraper
from functools import partial


class ActionArea(Tkinter.LabelFrame):

    def __init__(self, master, cnf={}, **kw):
        Tkinter.LabelFrame.__init__(self, master, cnf)
        self.register = {}
        self.actions = {}

    def collect_values(self):
        values = {}
        for name, widget in self.master.widgets.items():
            values[name] = widget.value
        for k, v in self.register.items():
            values['old_' + k] = v

        return {'params': values}

    def update(self, values, mode='search'):
        if mode == 'search':
            values = values[0] if values else {}
            self.register = values
            self.master.update(values)
        elif mode == 'update':
            values = self.actions['search'](self.register)
            self.update(values)
        elif mode == 'delete':
            self.register = {}
            self.master.update({})
        elif mode == 'add':
            values = self.actions['search'](self.collect_values()['params'])
            self.update(values)

    def add_action(self, name, callback):
        if name in ('search', 'update', 'delete', 'add'):
            func = MethodWraper(callback, None, partial(self.update,
                                 mode=name), self.collect_values)
        else:
            func = MethodWraper(callback, None, self.update,
                                self.collect_values)
        self.actions[name] = func

        button = Tkinter.Button(self, text=name, command=func)
        button.pack()

    def add_param(self, name):
        pass
